<template>
  <div v-loading="loading" class="app-container">
    <el-steps :active="active">
      <el-step title=" " description="系统基本信息"></el-step>
      <el-step title=" " description="填写资源申请"></el-step>
      <el-step title=" " description="服务清单送审"></el-step>
    </el-steps>
    <AddA ref="adda" @next="next" :dept="dept" v-show="active == 1" />
    <AddB
      ref="addb"
      @next="next"
      v-if="addBFlag"
      :configure="configure"
      :supplierCode="form.cloudUp.supplierCode"
      v-show="active == 2"
    />
    <AddC :form="form" v-show="active == 3" />
    <Process ref="process" :ind="0" style="margin-bottom: 10px" />
    <div style="display: flex; justify-content: flex-end">
      <el-button :loading="btnLoading" type="info" v-if="active > 1" @click="active--">上一步</el-button>
      <el-button :loading="btnLoading" type="primary" v-if="active == 3" @click="submitApply">提交审核</el-button>
      <el-button :loading="btnLoading" type="primary" v-else @click="next(false)">下一步</el-button>
      <el-button @click="ReturnSuperio">取 消</el-button>
    </div>
  </div>
</template>

<script>
import ApplyBefore from "@/components/Activiti/ApplyBefore/index";
import ApplyAfter from "@/components/Activiti/ApplyAfter/index";
import sDetails from "./details.vue";
import Examine from "./examine.vue";
import AddA from "./addA.vue";
import AddB from "./addB.vue";
import AddC from "./addC.vue";
import Process from "../../todoItem/todo/process.vue";
import { listDemo, getDemo, delDemo, addDemo, updateDemo, exportDemo } from "@/api/example/demo";
import { listUser } from "@/api/system/user";
import {
  resourcesUpList,
  resourcesUpDetail,
  apply,
  listByCode,
  serviceByClazz,
  classByCode,
  specEcs,
} from "@/api/resources/apply";
import { treeselect } from "@/api/system/dept";
import { getDicts } from "@/api/system/dict/data";
import { addCloudUp } from "@/api/cloud/cloud";
import { uploadFile } from "@/api/system/upload.js";
import request from "@/utils/request";
export default {
  name: "addapplysNoXc",
  components: {
    ApplyBefore,
    ApplyAfter,
    sDetails,
    Examine,
    AddA,
    AddB,
    AddC,
    Process,
  },
  data() {
    return {
      loading: false,
      btnLoading: false,
      addBFlag: false,
      // 申请步骤
      active: 0,
      //部门列表树结构
      dept: [],
      // 表单参数
      form: {
        //系统id
        cloudUpId: "",
        //系统基本信息
        cloudUp: {},
        cloudSupplier: "", //服务商
        cloudSupplier_label: "", //服务商名称
        hosts: [], //资源列表
        databases: [], //数据库列表
        storeProducts: [], //存储产品列表
        safeProducts: [], //安全产品列表
        remark: "", //说明
        files: [], //文件
        actionName: "发起申请",
      },
      //配置
      configure: {
        available_domain: [], //可用域
        cloud_service_provider: [], //服务商
        storage_type: [], //系统盘类型
        codeList: [], //云服务器规格列表
        czxtList: [], //操作系统列表
        ccList: [], //数据盘类型
        fwcpList: [], //服务型磁盘类型
        wlfwqList: [], //高性能服务器资源类型
        sjkList: [], //数据库类型
        yyaqList: [], //安全产品
        SpecificationsList: [],
      },
    };
  },
  watch: {
    // active:{
    //     handler(newName, oldName){
    //         if(newName == 2){
    //             this.getDataOfAdd()
    //         }
    //     }
    // }
  },
  created() {
    this.getListDept();
    // this.getDataOfAdd()
    this.active = 1;
    setTimeout(() => {
      this.$refs.process.init({
        definitionName: "资源申请",
        taskName: "资源申请",
      });
    }, 100);
  },
  mounted() {},
  methods: {
    // 返回上级--> 资源申请列表
    ReturnSuperio() {
      // this.$store.dispatch('filterAsyncRouter', this.$route);
      // this.$router.go(-1);
      this.$store.state.tagsView.visitedViews.splice(
        this.$store.state.tagsView.visitedViews.findIndex((item) => item.path === this.$route.path),
        1
      );
      this.$destroy("addapplysNoXc");
      this.$router.push("/resources/apply");
    },
    //部门列表
    getListDept() {
      treeselect({}).then((response) => {
        this.dept = response.data;
      });
    },
    getDataOfAdd() {
      this.loading = true;
      // 获取信创CPU或者内存规格
      specEcs({ Inspur: this.form.cloudUp.supplierCode }).then((res) => {
        this.configure.SpecificationsList = res.rows;
      });
      //可用域
      getDicts("available_domain").then((response) => {
        this.configure.available_domain = response.data;
      });
      //服务商
      getDicts("cloud_service_provider").then((response) => {
        this.configure.cloud_service_provider = response.data;
      });
      //盘类型
      serviceByClazz({ code: "cc", supplier: this.form.cloudUp.supplierCode }).then((response) => {
        response.data.forEach((item) => {
          if (["FCcc(tykcc)2", "FCcc_ssd", "spycc2"].indexOf(item.code) < 0) {
            this.configure.storage_type.push(item);
          }
          if (["spycc2"].indexOf(item.code) < 0) {
            this.configure.ccList.push(item);
          }
          if (["fbscc_wjcc2", "FCcc(tykcc)2", "FCcc_ssd"].indexOf(item.code) < 0) {
            this.configure.fwcpList.push(item);
          }
        });
      });
      //操作系统
      classByCode({ code: "czxt" }).then((response) => {
        this.configure.czxtList = response.data;
      });
      // //云服务器规格列表
      // listByCode("spec_ecs").then((response) => {
      //     this.configure.codeList = response.data;
      // });
      //高性能服务器资源类型列表
      serviceByClazz({ code: "wlfwq", supplier: this.form.cloudUp.supplierCode }).then((response) => {
        this.configure.wlfwqList = response.data;
      });
      //数据库类型列表
      serviceByClazz({ code: "sjk", supplier: this.form.cloudUp.supplierCode }).then((response) => {
        this.configure.sjkList = response.data;
      });
      //安全产品列表
      serviceByClazz({ code: "yyaq", supplier: this.form.cloudUp.supplierCode }).then((response) => {
        this.configure.yyaqList = response.data;
      });
      setTimeout(() => {
        this.loading = false;
      }, 100);
    },
    //下一步
    next(data) {
      if (data) {
        if (this.active == 1) {
          this.$refs.addb.DefaultServiceProvider(data);
        }
        if (this.active == 1) {
          if (data.cloudUpId) {
            this.form.cloudUpId = data.cloudUpId;
          } else {
            this.form.cloudUpId = "";
            data.fundBySelf = data.fundBySelf == "1" ? true : false;
            if (data.fundFromRadio == "1") {
              data.fundFrom = "区（县）";
            } else if (data.fundFromRadio == "2") {
              data.fundFrom = "市级";
            }
          }
          this.form.cloudUp = data;
          this.getDataOfAdd(data);
        } else if (this.active == 2) {
          this.form.cloudSupplier = data.cloudSupplier;
          this.form.cloudSupplier_label = data.cloudSupplier_label;
          this.form.hosts = data.hosts;
          this.form.databases = data.databases;
          this.form.storeProducts = data.storeProducts;
          this.form.safeProducts = data.safeProducts;
          this.form.remark = data.remark;
          this.form.files = data.fileList;
        }
        this.active++;
      } else if (this.active == 1) {
        this.addBFlag = true;
        this.$nextTick(() => {
          this.$refs.adda.next();
        });
      } else if (this.active == 2) {
        this.$refs.addb.next();
      } else {
        this.submitApply();
      }
    },
    /** 提交申请 */
    submitApply() {
      this.$confirm("是否确认提交?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.btnLoading = true;
        let form = JSON.parse(JSON.stringify(this.form));
        if (this.form.files && this.form.files.length) {
          var param = new FormData();
          param.append("key", "file");
          this.form.files.forEach((item) => {
            param.append("file", item.raw);
          });
          if (this.form.cloudUp.files && this.form.cloudUp.files.length && this.form.cloudUp.files[0].raw) {
            var cloudUpparam = new FormData();
            cloudUpparam.append("key", "file");
            this.form.cloudUp.files.forEach((item) => {
              cloudUpparam.append("file", item.raw);
            });
            uploadFile(cloudUpparam)
              .then((ress) => {
                form.cloudUp.files = ress.data;
                uploadFile(param)
                  .then((res) => {
                    form.files = res.data;
                    form.actionName = "发起申请";
                    this.sub(form);
                  })
                  .catch((e) => {
                    this.btnLoading = false;
                  });
              })
              .catch((e) => {
                this.btnLoading = false;
              });
          } else {
            uploadFile(param)
              .then((res) => {
                form.files = res.data;
                form.actionName = "发起申请";
                this.sub(form);
              })
              .catch((e) => {
                this.btnLoading = false;
              });
          }
        } else {
          if (this.form.cloudUp.files && this.form.cloudUp.files.length && this.form.cloudUp.files[0].raw) {
            var cloudUpparam = new FormData();
            cloudUpparam.append("key", "file");
            this.form.cloudUp.files.forEach((item) => {
              cloudUpparam.append("file", item.raw);
            });
            uploadFile(cloudUpparam)
              .then((res) => {
                form.cloudUp.files = res.data;
                form.actionName = "发起申请";
                this.sub(form);
              })
              .catch((e) => {
                this.btnLoading = false;
              });
          } else {
            form.actionName = "发起申请";
            this.sub(form);
          }
        }
      });
    },
    sub(form) {
      form.hosts.forEach((item) => {
        item.instanceName = item.hostName;
      });
      form.officeId = form.cloudUp.officeId;
      form.isXc = false;
      if (!form.cloudUpId) {
        addCloudUp(form.cloudUp).then((re) => {
          form.cloudUpId = re.data.id;
          delete form.cloudUp;
          apply({ formObject: form })
            .then((res) => {
              this.$message({
                message: "提交成功",
                type: "success",
              });
              this.$store.state.tagsView.visitedViews.splice(
                this.$store.state.tagsView.visitedViews.findIndex((item) => item.path === this.$route.path),
                1
              );
              this.$destroy(this.$options.name);
              this.$router.push("/resources/apply");
            })
            .finally(() => {
              this.btnLoading = false;
            });
        });
      } else {
        delete form.cloudUp;
        apply({ formObject: form })
          .then((res) => {
            this.$message({
              message: "提交成功",
              type: "success",
            });
            this.$store.state.tagsView.visitedViews.splice(
              this.$store.state.tagsView.visitedViews.findIndex((item) => item.path === this.$route.path),
              1
            );
            this.$destroy(this.$options.name);
            this.$router.push("/resources/apply");
          })
          .finally(() => {
            this.btnLoading = false;
          });
      }
    },
  },
};
</script>
